package com.ham.mud.commands;

import com.ham.mud.ServerConnection;
import com.ham.mud.TargetableService;
import com.ham.mud.characters.mobs.Mob;
import com.ham.mud.characters.npcs.VendorNPC;
import com.ham.mud.characters.player.Player;
import com.ham.mud.items.Item;
import com.ham.mud.items.ItemService;
import com.ham.mud.rooms.Room;
import com.ham.mud.rooms.RoomService;

import java.util.List;

/**
 * Created by hlucas on Jul 19, 2011 at 10:26:43 AM
 */
public class BuyCommand extends PlayerCommand {
    @Override
    public void execute(ServerConnection connection, String[] params) {
        Room room = RoomService.getRoom(connection);
        List<Mob> mobs = room.getMobs();
        VendorNPC npc = null;
        for(Mob mob : mobs) {
            if(mob instanceof VendorNPC) {
                npc = (VendorNPC) mob;
                break;
            }
        }

        if(npc == null) {
            connection.printSolo("This is not a shop.");
            return;
        }

        if(params.length == 0) {
            connection.printSolo("Buy what?");
            return;
        }

        List<Item> npcInventory = npc.getInventory();
        Item item = (Item) TargetableService.findTarget(params[0], npcInventory);
        if(item == null) {
            connection.printSolo("That isn't being sold here.");
            return;
        }

        int price = item.getPrice();
        Player player = connection.getPlayer();
        if(player.getGold() < price) {
            connection.printSolo("You cannot afford " + item.getName() + ".");
            return;
        }

        player.decrementGold(price);
        player.addItem(ItemService.getItem(item.getFileName()));
        connection.printSolo("You purchase " + item.getName() + " from " + npc.getName() + " for " + price + " gold.");
    }

    @Override
    protected String getCommandName() {
        return "buy";
    }
}
